import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME,
	HEADERPARAMS
} from '@/config/app';
import {
	toLogin,
	checkLogin
} from '../libs/login';
import store from '../store';

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}, params) {
	let Url = HTTP_REQUEST_URL;
	let header = {
		...HEADER
	};

	if (params != undefined) {
		header = {
			...HEADERPARAMS
		};
	}

	// 添加 token 到 header 中
	if (store.state.app.token) {
		header[TOKENNAME] = store.state.app.token;
	}

	// // 动态添加 storeId 到 header 中
	// const storeId = uni.getStorageSync('storeId');

	// // 检查 storeId 是否为非空字符串
	// if (storeId !== null && storeId !== undefined && storeId !== "") {
	// 	header['store'] = storeId; // 使用 'store' 字符串作为键名
	// }

	return new Promise((resolve, reject) => {
		uni.request({
			url: Url + '/' + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if (noVerify || res.data.code === 200) {
					resolve(res.data);
				} else if ([410000, 410001, 410002, 401].includes(res.data.code)) {
					reject(res.data);
				} else if (res.data.code === 600) {
					if (res.data.msg == "您暂时未拥有推广权限") {
						uni.showModal({
							title: '提示',
							content: res.data.msg,
							showCancel: false,
							confirmText: '确定',
							success: () => {
								uni.switchTab({
									url: '/pages/platform/index'
								})
							}
						});
					} else {
						uni.showModal({
							title: '提示',
							content: res.data.msg,
							showCancel: false,
							confirmText: '确定',
							success: () => {
								reject(res.data.msg);
							}
						});
					}
				} else {
					reject(res.data.message || '系统错误');
				}
			},
			fail: (error) => {
				reject('请求失败');
			}
		});
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt = {}, params) => baseRequest(api, method.toUpperCase(), data, opt,
		params);
});

export default request;